package com.wasp.collector.service.chain;

import java.io.File;
import java.io.IOException;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.wasp.collector.utils.FileOperator;
import com.wasp.collector.utils.IConstant;
import com.wasp.collector.utils.PropertiesUtil;
import com.wasp.collector.utils.StringUtils;

public class FileHandleChain extends AbstractHandleChain{
	private String fileName = "";
	private String path=  "";
	boolean isAutoGenerateFileName = false;
	public FileHandleChain(IFileRule rule){
		if(rule != null){
			path = rule.pathRule();
		}
	}
	/*private void setPath(String path){
		this.path = path;
	}*/
	public FileHandleChain(IFileRule rule,String fileName){
		this(rule);
		if(!StringUtils.isNullOrEmpty(fileName)){
			isAutoGenerateFileName = true;
			this.fileName = fileName;
		}
	}
	@Override
	protected void realHandleRequest() {
		if(needHandleData == null){
			return;
		}
		fileName = generateFileName();
		path = (String) getRequestContext().getContext().get(IConstant.PATH);
		String baseFolder = PropertiesUtil.loadProperies().getProperty("basefile");
		String basePath = baseFolder+path ;
		File file = new File(basePath);
		if(!file.exists()){
			file.mkdirs();
		}
		String fileCompletePath = basePath + File.separator + fileName;
		Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
		try {
			FileOperator.createFile(gson.toJson(needHandleData), fileCompletePath,basePath);
		} catch (IOException e) {
			log.error(this.getClass().getName(),e);
		}
	}
	private String generateFileName(){
		if(isAutoGenerateFileName){
			return fileName;
		}
		fileName = (String) getRequestContext().getContext().get(IConstant.FILENAME);
		if(StringUtils.isNullOrEmpty(fileName)){
			fileName = StringUtils.generateUUID();
		}
		return fileName;
	}
    
}